package controller;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet(urlPatterns = "/download")
public class DownLoadController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String fileName = request.getParameter("download");
        String filePath = request.getServletContext().getRealPath("upload") + File.separator + fileName;
        FileInputStream fileInputStream = new FileInputStream(filePath);

        response.setHeader("Content-Disposition", "attachment; filename="+filePath);
        ServletOutputStream outputStream = response.getOutputStream();

        int length=0;
        byte [] bytes = new byte[1024];

        while ((length=fileInputStream.read(bytes))>0){
            outputStream.write(bytes,0,length);
        }

        outputStream.close();

    }
}
